package com.eastedu.util;

import com.eastedu.exception.ServiceException;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 参数校验工具类
 *
 * @author 张志帅
 */
public final class AssertUtil {

    private AssertUtil() {
    }

    /**
     * Not null.
     *
     * @param object  the object
     * @param message the message
     */
    public static void notNull(@Nullable Object object, String message) {
        if (object == null) {
            throw new ServiceException(message);
        }
    }

    /**
     * Has text.
     *
     * @param text    the text
     * @param message the message
     */
    public static void hasText(@Nullable String text, String message) {
        if (!StringUtils.hasText(text)) {
            throw new ServiceException(message);
        }
    }

    /**
     * Has length.
     *
     * @param text    the text
     * @param message the message
     */
    public static void hasLength(@Nullable String text, String message) {
        if (!StringUtils.hasLength(text)) {
            throw new ServiceException(message);
        }
    }

    /**
     * Not empty.
     *
     * @param collection the collection
     * @param message    the message
     */
    public static void notEmpty(@Nullable Collection<?> collection, String message) {
        if (CollectionUtils.isEmpty(collection)) {
            throw new ServiceException(message);
        }
    }

    /**
     * Contains.
     *
     * @param <T>        the type parameter
     * @param collection the collection
     * @param element    the element
     * @param message    the message
     */
    public static <T> void contains(List<T> collection, T element, String message) {
        if (ObjectUtils.isEmpty(element) || !collection.contains(element)) {
            throw new ServiceException(message);
        }
    }

    /**
     * Equals.
     *
     * @param obj1    the obj 1
     * @param obj2    the obj 2
     * @param message the message
     */
    public static void notEquals(Object obj1, Object obj2, String message) {
        if (Objects.equals(obj1, obj2)) {
            throw new ServiceException(message);
        }
    }

    /**
     * Is true.
     *
     * @param result  the result
     * @param message the message
     */
    public static void isTrue(boolean result, String message) {
        if (!result) {
            throw new ServiceException(message);
        }
    }
}
